#include "config.h"
#include "isr.h"

#define SYSTICK
// #define EXTI
// #define TIMER
#define UART

#ifdef SYSTICK
// SysTick interrupt handler - called every 1 ms (configured by SysConfig)
void SysTick_Handler(void)
{
	msTicks++;
}
#endif

#ifdef EXTI
/*
 * Group1 IRQ handler handles GPIOA interrupts among others.
 * SysConfig enabled PA7 (GPIOA pin 7) as falling edge interrupt.
 */
void GROUP1_IRQHandler(void)
{
	/* Check if GPIOA PA7 triggered (enabled interrupt status) */
	if (DL_GPIO_getEnabledInterruptStatus(ENCODER_PORT, ENCODER_EC11_KEY_PIN) & ENCODER_EC11_KEY_PIN)
	{
		/* Clear the interrupt flag for PA7 */
		DL_GPIO_clearInterruptStatus(ENCODER_PORT, ENCODER_EC11_KEY_PIN);
		/* Set a flag for the main loop or other tasks to process */
		encoderEvent = 1;
	}

	/* If other Group1 sources exist, optionally check/clear them here.
	 * DL_Interrupt_getStatusGroup and DL_Interrupt_clearGroup can be used
	 * for group-level handling if needed.
	 */
}

#endif

#ifdef TIMER

void TIM0_INST_IRQHandler(void)
{
	/* Check if TIM0 update interrupt is pending */
	if (DL_Timer_getPendingInterrupt(TIM0_INST) & DL_TIMERA_INTERRUPT_LOAD_EVENT)
	{
		/* Clear the interrupt flag */
		DL_Timer_clearInterruptStatus(TIM0_INST, DL_TIMERA_INTERRUPT_LOAD_EVENT);

		// 原始按键读取：0 = 按下，1 = 释放
		uint8_t raw = (DL_GPIO_readPins(ENCODER_PORT, ENCODER_EC11_KEY_PIN) & ENCODER_EC11_KEY_PIN) ? 1 : 0;

		// 8-bit 移位寄存器消抖（每1ms采样一次 8ms 为一个窗口）
		static uint8_t key_hist = 0xFF;
		static uint8_t key_stable = 1; // 1 表示稳定，初始状态为稳定释放

		key_hist = (uint8_t)((key_hist << 1) | raw);

		if (key_hist == 0x00 && key_stable != 0)
		{
			key_stable = 0;
			keyPressEvent = 1; // 稳定按下事件
		}
		else if (key_hist == 0xFF && key_stable != 1)
		{
			key_stable = 1;
			// 可设置释放事件（如需）
		}
	}
}

#endif

#ifdef UART
void UART_0_INST_IRQHandler(void)
{
	// Check if RX interrupt is pending
	if (DL_UART_getPendingInterrupt(UART_0_INST) & DL_UART_IIDX_RX)
	{
		// Read the received byte
		uint8_t dat;
		dat = DL_UART_Main_receiveData(UART_0_INST);

		switch (uart_sm)
		{
		case 0:
		{
			if (dat == 'o')
				uart_sm = 1;
		}
		break;
		case 1:
		{
			if (dat == 'n')
			{
				DL_GPIO_clearPins(LED_PORT, LED_LED_0_PIN);
				uart_sm = 0;
				UART0_flag = 1;
			}
			else if (dat == 'f')
			{
				uart_sm = 2;
			}
			else
			{
				uart_sm = 0;
			}
		}
		break;
		case 2:
		{
			if (dat == 'f')
			{
				DL_GPIO_setPins(LED_PORT, LED_LED_0_PIN);
				UART0_flag = 1;
			}
			uart_sm = 0; // 状态机归零
		}
		break;
		default:
			uart_sm = 0;
			break; // 状态机归零
		}
		// Clear RX interrupt flag
		DL_UART_Main_clearInterruptStatus(UART_0_INST, DL_UART_MAIN_INTERRUPT_RX);
	}
	// Optionally handle TX interrupt if implemented
}
#endif